package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;


import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;


import java.util.UUID;
@Slf4j
@Service
public class FileUploadServiceImpl  implements FileUploadService {


    @Autowired
    private MinioConstantProperties minioConstantProperties;

    @Autowired
    private MinioClient minioClient;
    @Override
    @SneakyThrows  //Lombok中对异常进行处理的注解
    public String uploadFile(MultipartFile file){


        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
        if (!found) {
            // Make a new bucket called 'asiatrip'.
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
        }

        //创建一个UUID作为文件名称
        String fileName = UUID.randomUUID().toString().replace("-","");
        //获取文件的格式
        String originalFilename = file.getOriginalFilename();
        String extName = FilenameUtils.getExtension(originalFilename);
        String fulFileName = fileName+"."+extName;

        //上传文件
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(minioConstantProperties.getBucketName())
                .stream(file.getInputStream() , file.getSize() , -1)
                .object(fulFileName)
                .build();
        minioClient.putObject(putObjectArgs);

        //构建文件的文件访问地址
        String url = minioConstantProperties.getEndpointUrl()+"/"+minioConstantProperties.getBucketName()+"/"+fulFileName;

        log.info("文件上传成功了，访问地址为：{}" , url);

        return url;
    }
}
